const  mongoose =  require('../utils/mongooseConnection');
var express = require('express');
var router = express.Router();
const Cache = require('../utils/cache');

const bodyParser = require('body-parser');
//创建 application/x-www-form-urlencoded 编码解析
const urlencodedParser = bodyParser.urlencoded({ extended: false });

var responseJSON = function (res, ret) {
	if(typeof ret === 'undefined') { 
		res.json({ code:'-200', msg: '操作失败' }); 
	} else { 
		res.json(ret); 
	}
};

/**
 * 定义Schema
 */
var stuSchema = new mongoose.Schema({
		studentNo:String,
		studentName:String,
		sex:{type:String,default:'男'},
		age:{type:Number,default:18},
		gradeId:{type:Number},
		address:String
	},
	{
		versionKey:false,
		collection:'student'
	}
)

/**
 * 定义model
 */
const stuModel = mongoose.model('student', stuSchema);


router.post('/save',urlencodedParser,function(req,res,next){
	let params = req.method == "POST"?req.body:req.query || req.params;
	
	var doc = ({
		studentNo:params.studentNo,
		studentName:params.studentName,
		sex:params.sex,
		age:params.age,
		gradeId:params.gradeId,
		address:params.address
	})
	
	console.log(params.studentNo+'/'+params.studentName+'/'+params.sex+'/'+params.age+'/'+params.gradeId+'/'+params.address);
	stuModel.create(doc,(err,docs)=>{
		if(err){
    		throw new Error();
    		return;
	    } 
	    if(docs){
        	 responseJSON(res,{code: 200,msg:'操作成功'});
        }
	})
})

router.post('/update',urlencodedParser,function(req,res,next){
	let params = req.method == "POST"?req.body:req.query || req.params;
	
	var doc = ({
		studentNo:params.studentNo,
		studentName:params.studentName,
		sex:params.sex,
		age:params.age,
		gradeId:params.gradeId,
		address:params.address
	})
	
	console.log(params.studentNo+'/'+params.studentName+'/'+params.sex+'/'+params.age+'/'+params.gradeId+'/'+params.address);
	stuModel.findByIdAndUpdate({_id:params.id},
		{studentNo:params.studentNo,studentName:params.studentName,sex:params.sex,age:params.age,gradeId:params.gradeId,address:params.address},
		(err,docs)=>{
		if(err){
    		throw new Error();
    		return;
	    } 
	    if(docs){
        	 responseJSON(res,{code: 200,msg:'操作成功'});
        }
	})
})

/**
 * 基于嵌套实现
 */
router.post('/student_list_join',urlencodedParser, function(req, res, next) {
	let params = req.method == "POST"?req.body:req.query || req.params;
	let pageNo = params.pageno;
	let pageSize = parseInt(params.pagesize); // 每一页显示的数据条数  
	let start = parseInt((pageNo-1)*pageSize);// 这边可以改为接收参数后的计算  start = (页数-1)*pageSize;
	
  	stuModel.find().skip(start).limit(pageSize).populate({
  			path:'gradeId',model:'grade',
  			select:'studenNo studentName sex age gradeName address'
  		}).exec(
		(err, docs)=>{
		    if(err){
		    	throw new Error();
		    	return;
		    } 
		    //console.log('查询结果：' + docs);
		    if(res.length==0){
		   		res.json({ code:'-200', msg: '根据请求没有获取到相应的数据!'}); 
			}else{
				stuModel.count({},(err,dc)=>{
					if(err){
					    throw new Error();
					    return;
					}
					res.json({msg:'数据已返回',status:'200',result:docs,count:dc}); 
				})
			}
	});
});

/**
 * 基于Promises实现
 */
router.post('/student_list_new',urlencodedParser, function(req, res, next) {
		let params = req.method == "POST"?req.body:req.query || req.params;
		let pageNo = params.pageno;
		let pageSize = parseInt(params.pagesize); // 每一页显示的数据条数  
		let start = parseInt((pageNo-1)*pageSize);// 这边可以改为接收参数后的计算  start = (页数-1)*pageSize;
		
		console.log('start:',start);
		console.log('pageSize:',pageSize);
		
  	stuModel.find().skip(start).limit(pageSize).populate({
  			path:'gradeId',model:'grade',
  			select:'studenNo studentName sex age gradeName address'
  		}).exec()
  		.then(function(docs){
  			var result = [];
  			return stuModel.count({}).exec()
  			.then(function(count){
  				return [docs, count]
  			})
  		})
  		.then(function(result){
  			var docs = result[0];
  			var count = result[1];
  			res.json({msg:'数据已返回',status:'200',result:docs,count:count});
  		});
});


/* GET users listing. */
router.get('/student_list', function(req, res, next) {
  	stuModel.find(
		{}, 
		{studentNo: 1, studentName: 1, sex: 1,age:1,gradeId:1,address:1}, 
		(err, docs)=>{
	    if(err){
	    	throw new Error();
	    	return;
	    } 
	    //console.log('查询结果：' + docs);
	    if(res.length==0){
	   		res.json({ code:'-200', msg: '根据请求没有获取到相应的数据！' }); 
		} else { 
			res.json({msg:'数据已返回',status:'200',result:docs});
		}
	})
});

router.get('/readOne', function(req, res, next) {
	let params = req.method == "POST"?req.body:req.query || req.params;
	let _stuid = params.id;
	console.log('_stuid:',_stuid)
  	stuModel.findById(
		{_id:_stuid}, 
		{studentNo: 1, studentName: 1, sex: 1,age:1,gradeId:1,address:1}, 
		(err, docs)=>{
	    if(err){
	    	throw new Error();
	    	return;
	    } 
	    //console.log('查询结果：' + docs);
	    if(res.length==0){
	   		res.json({ code:'-200', msg: '根据请求没有获取到相应的数据！' }); 
		} else { 
			res.json({msg:'数据已返回',status:'200',result:docs});
		}
	})
});




router.post('/delete',urlencodedParser, function(req, res, next) {
	let params = req.method == "POST"?req.body:req.query || req.params;
	let _stuid = params.id;
	console.log('_stuid:',_stuid)
	stuModel.findByIdAndRemove({_id:_stuid},(err,docs)=>{
		if(err){
	    	throw new Error();
	    	return ;
	    } 
	    console.log('操作成功：' + docs);
	     if(res.length==0){
	   		res.json({ code:'-200', msg: '操作失败！' }); 
		} else { 
			res.json({msg:'操作成功！',status:'200'});
		}
	})
 
});


module.exports = router;